<template>
  <div>
    <vue-editor
      useCustomImageHandler
      @image-added="handleImageAdded"
      v-model="content"
      :editorToolbar="customToolbar"/>
  </div>
</template>

<script>
import {VueEditor} from 'vue2-editor'
import Vue from 'vue'

export default {
  name: 'MyEditor',
  components: {VueEditor},
  props: {
    callBack: Function
  },
  data: function () {
    return {
      content: '',
      customToolbar: [
        [{
          header: [false, 1, 2, 3, 4, 5, 6]
        }],
        ['bold', "italic", "underline", "strike"],
        [{color: []}, {background: []}],
        [{list: 'ordered'}, {list: 'bullet'}],
        ['image', 'code-block']
      ]
    }
  },
  watch: {
    // 监听内容变化
    content: function (value) {
      if (typeof this.$props.callBack) {
        this.$props.callBack(this.content)
      }
      // console.log('内容变化',this.content)
    }
  },
  methods: {
    // 设置内容
    setContent: function (content) {
      this.content = content
      this.$forceUpdate()
    },
    // editor处理上传图片
    handleImageAdded: function (file, Editor, cursorLocation, resetUploader) {
      // An example of using FormData
      // NOTE: Your key could be different such as:
      // formData.append('file', file)
      var header = this.getHeader()
      header['Content-Type'] = 'multipart/form-data'
      var formData = new FormData()
      formData.append('myUploadFile', file)
      this.$http.post(this.UploadFileUrl, formData, {
        emulateJSON: true,
        credentials: true,
        headers: header
      }).then(function (response) {
        console.log('response', response)
        const url = response.data.data // Get url from response
        Editor.insertEmbed(cursorLocation, 'image', url)
        resetUploader()
      }, function (errorResponse) {
        Vue.MyRequestLoading[url] = false
        console.error('--------------------------http-请求错误--------------------------')
        console.log(JSON.stringify(errorResponse))
      })

    }
  }
}
</script>

<style scoped>

</style>
